<template>
  <div class="permission-manage">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.permissionName"
            placeholder="搜索权限名称"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="searchForm.createTime"
            type="date"
            placeholder="选择创建时间"
            clearable
            @change="handleSearch"
          />
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 权限列表 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column type="index" width="60" label="序号" />
      
      <el-table-column prop="permissionName" label="权限名称" min-width="120">
        <template #default="{ row }">
          <el-tag effect="plain">{{ row.permissionName }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="permissionKey" label="权限标识" min-width="120">
        <template #default="{ row }">
          <span>{{ row.permissionKey }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="url" label="权限URL" min-width="120">
        <template #default="{ row }">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="description" label="描述" min-width="200">
        <template #default="{ row }">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            link
            @click="handleEdit(row)"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            link
            @click="handleDelete(row.id)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="权限名称" prop="permissionName">
          <el-input
            v-model="formData.permissionName"
            placeholder="请输入权限名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="权限标识" prop="permissionKey">
          <el-input
            v-model="formData.permissionKey"
            placeholder="请输入权限标识"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="权限URL" prop="url">
          <el-input
            v-model="formData.url"
            placeholder="请输入权限URL"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入权限描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  Search,
  Plus,
  Refresh,
  Edit,
  Delete
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  permissionName: '',
  createTime: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: null,
  permissionName: '',
  permissionKey: '',
  url: '',
  description: ''
})

// 表单验证规则
const formRules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 1, max: 100, message: '权限名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  permissionKey: [
    { required: true, message: '请输入权限标识', trigger: 'blur' },
    { min: 1, max: 100, message: '权限标识长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入权限URL', trigger: 'blur' },
    { min: 1, max: 200, message: '权限URL长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入权限描述', trigger: 'blur' },
    { min: 1, max: 200, message: '权限描述长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return formData.id ? '编辑权限' : '新增权限'
})

// 生命周期
onMounted(() => {
  loadTableData()
})

// 加载表格数据（仅保留1个，删除重复声明）
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/PermissionAll', {
      params: {
        current: pagination.currentPage,
        pageSize: pagination.pageSize,
        permissionName: searchForm.permissionName
      }
    })
    // 适配后端分页数据格式（根据实际返回调整，此处假设返回 { data: { records: [], total: 0 } }）
    tableData.value = response.data.data?.records || []
    pagination.total = response.data.data?.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

// 刷新
const handleRefresh = () => {
  loadTableData()
  ElMessage.success('刷新成功')
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑（补充url字段赋值，避免漏填）
const handleEdit = (row) => {
  resetForm()
  Object.assign(formData, {
    id: row.id,
    permissionName: row.permissionName,
    permissionKey: row.permissionKey,
    url: row.url, // 补充漏写的url字段
    description: row.description
  })
  dialogVisible.value = true
}

// 删除（仅保留1个，删除重复声明）
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这个权限吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.delete(`/DeletePermission/${id}`)
      if (response.data.success) {
        ElMessage.success('删除成功')
        loadTableData()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 提交表单（仅保留1个，删除重复声明）
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const url = formData.id ? '/UpdatePermission' : '/AddPermission'
        const response = await axios.post(url, formData)
        if (response.data.success) {
          ElMessage.success(formData.id ? '更新成功' : '新增成功')
          dialogVisible.value = false
          loadTableData()
        } else {
          ElMessage.error(response.data.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 重置表单（补充url字段重置）
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    permissionName: '',
    permissionKey: '',
    url: '', // 补充漏写的url字段重置
    description: ''
  })
}

// 格式化日期时间（简单实现，可根据需要用dayjs优化）
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadTableData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}
</script>

<style scoped>
.permission-manage {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-table) {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>